package com.seveneight.baijiesteward.ui.user.fragment;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseFragment;
import com.seveneight.baijiesteward.base.BaseFragmentBack;
import com.seveneight.baijiesteward.base.MessageBean;
import com.seveneight.baijiesteward.base.MessageEvent;
import com.seveneight.baijiesteward.base.SDKConfig;
import com.seveneight.baijiesteward.bean.AnyBean;
import com.seveneight.baijiesteward.bean.BaseEntity;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.http.HttpConfig;
import com.seveneight.baijiesteward.ui.main.activity.MainActivity;
import com.seveneight.baijiesteward.ui.user.contract.GetBankListContract;
import com.seveneight.baijiesteward.ui.user.contract.IdentifyContract;
import com.seveneight.baijiesteward.ui.user.contract.UploadInfoContract;
import com.seveneight.baijiesteward.ui.user.fragment.identify.IdentifyFragment1;
import com.seveneight.baijiesteward.ui.user.fragment.identify.IdentifyFragment2;
import com.seveneight.baijiesteward.ui.user.fragment.identify.IdentifyFragment3;
import com.seveneight.baijiesteward.ui.user.presenter.GetBankListPresenter;
import com.seveneight.baijiesteward.ui.user.presenter.IdentifyPresenter;
import com.seveneight.baijiesteward.ui.user.presenter.UploadInfoPresenter;
import com.seveneight.baijiesteward.utils.BankCarLegal;
import com.seveneight.baijiesteward.utils.CrossUtil;
import com.seveneight.baijiesteward.utils.HttpClientUtil;
import com.seveneight.baijiesteward.utils.HttpUpload;
import com.seveneight.baijiesteward.utils.IDCardLegal;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.PhoneFormatCheckUtils;
import com.seveneight.baijiesteward.utils.StringUtils;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.utils.WaterMaskUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by user1 on 2018/2/23.
 */

public class IdentifyFragment extends BaseFragmentBack implements View.OnClickListener, EasyPermissions.PermissionCallbacks, IdentifyContract.IdentifyView, UploadInfoContract.UploadInfoView {

    UploadInfoContract.UploadInfoPresenter uploadInfoPresenter;
    private int[] imgs = {R.mipmap.step1, R.mipmap.step2, R.mipmap.step3};
    private ImageView iv_back;
    private TextView tv_title;
    private FrameLayout layout_content;
    private Button bt_next;
    private ImageView iv_step;
    private List<BaseFragmentBack> fragments;
    private BaseFragmentBack allFragments;
    private BaseFragmentBack baseFragment;
    private static final int REQUEST__PERMISSIONS = 1;
    private IdentifyContract.IdentifyPresenter identifyPresenter;
    public static int STEP = 1;
    private int page = 0;
    public static String IMGSPATH1 = "";
    public static String IMGSPATH2 = "";
    public static String IMGSPATH3 = "";
    public static String RealName = "";
    public static String IdCardNo = "";
    public static String BankMobile = "";
    public static String BankCardNo = "";
    public static String BankId = "";
    public static String IdCardImgUrl = "";
    public static String BankCardImgUrl = "";
    public static String HoldIdCardImgUrl = "";
    public static String EMAIL = "";
    public static String ADDRESS = "";
    private CrossUtil crossUtil;


    private HttpUpload upload;
    private int SUCCESS_CODE = 1;
    private int FAIL_CODE = 2;

    public static IdentifyFragment newInstance() {
        Bundle args = new Bundle();
        IdentifyFragment fragment = new IdentifyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentView() {
        return R.layout.fragment_identify;
    }

    @Override
    protected void initView() {
        iv_step = findView(R.id.iv_step);
        iv_back = findView(R.id.iv_back);
        tv_title = findView(R.id.tv_title);
        layout_content = findView(R.id.layout_content);
        bt_next = findView(R.id.bt_next);
        tv_title.setText("实名认证");
//        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {
        fragments = new ArrayList<>();
        fragments.add(new IdentifyFragment1());
        fragments.add(new IdentifyFragment2());
        fragments.add(new IdentifyFragment3());
        identifyPresenter = new IdentifyPresenter(this);
        uploadInfoPresenter = new UploadInfoPresenter(this);
        crossUtil = new CrossUtil(mContext);
        transFragment();
    }

    @Override
    protected void setListener() {
        iv_back.setOnClickListener(this);
        bt_next.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (page==0){
                    _mActivity.onBackPressed();
                }else {
                    page--;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            iv_step.setImageResource(imgs[page]);
                            baseFragment = getFragment(page);
                            if (page==0){
                                STEP=2;
                            }else if(page==1){
                                STEP=4;
                            }else {
                                STEP=6;
                            }
//                            STEP--;
                            switchFragment(allFragments, baseFragment);
                        }
                    });
                }
                break;
            case R.id.bt_next:
                reBackData();
                break;
        }
    }

    private void reBackData() {
        if (StringUtils.isEmpty(IMGSPATH1)) {
            showDialog("请扫描身份证");
            return;
        }
        if (STEP == 2 || STEP == 1) {
            if (StringUtils.isEmpty(IMGSPATH1)){
                showDialog("请扫描身份证");
                return;
            }
            if (TextUtils.isEmpty(RealName)) {
                showDialog("请手动输入姓名");
                return;
            }
            if (TextUtils.isEmpty(IdCardNo)) {
                showDialog("请手动输入身份证号");
                return;
            }
            try {
                if (!IDCardLegal.IDCardValidate(IdCardNo)) {
                    showDialog("请输入有效身份证号");
                    return;
                }
            } catch (Exception ex) {

            }
            showLoading("正在上传照片...");
            page = 1;
            crossImg(IMGSPATH1);
        }
        if (STEP == 4 || STEP == 3) {
            if (StringUtils.isEmpty(IMGSPATH2)) {
                showDialog("请扫描银行卡");
                return;
            }
            if (TextUtils.isEmpty(BankId)) {
                showDialog("请手动选择银行");
                return;
            }
            if (!BankCarLegal.luhmCheck(BankCardNo)) {
                showDialog("请输入有效银行卡号");
                return;
            }
            if (TextUtils.isEmpty(BankMobile)) {
                showDialog("请输入银行预留手机号");
                return;
            }
            if (!PhoneFormatCheckUtils.isChinaPhoneLegal(BankMobile)) {
                showDialog("请输入有效手机号");
                return;
            }
            showLoading("正在上传照片...");
            page = 2;
            crossImg(IMGSPATH2);
        }
        if (STEP == 6 || STEP == 5) {
            if (StringUtils.isEmpty(IMGSPATH3)) {
                showDialog("请上传手持身份证照片");
                return;
            }
//            if (TextUtils.isEmpty(EMAIL)) {
//                showDialog("请输入邮箱地址");
//                return;
//            }
            if (!StringUtils.isEmpty(EMAIL)){
                if (!PhoneFormatCheckUtils.checkEmail(EMAIL)) {
                    showDialog("请输入有效的邮箱地址");
                    return;
                }
            }
            if (TextUtils.isEmpty(ADDRESS)) {
                showDialog("请输入住址");
                return;
            }
            showLoading("正在上传照片...");
            page = 3;
            crossImg(IMGSPATH3);
        }
    }


    @Override
    public void reBackUrl(String url) {

    }

    @Override
    public void identifySuccess(UserBean userBean) {
        hideLoading();
        showDialog("提交成功,请等待审核");
        setting.setUserInfo(userBean);
        EventBus.getDefault().post(new MessageEvent(1));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                _mActivity.onBackPressed();
            }
        }, 1000);
    }

    private void transFragment() {
        if (page == 3) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    startIdentify();
                    startUpdateInfo();
                }
            });
        } else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    iv_step.setImageResource(imgs[page]);
                    baseFragment = getFragment(page);
//                    STEP=(page+1)*2;
                    STEP++;
                    switchFragment(allFragments, baseFragment);
                }
            });
        }
    }

    private void startUpdateInfo() {
        uploadInfoPresenter.uploadInfo(mContext, jsonFormat.updateInfo(EMAIL, ADDRESS));
    }

    private void startIdentify() {
        LogUtil.d("RealName:" + RealName);
        LogUtil.d("IdCardNo:" + IdCardNo);
        LogUtil.d("BankMobile:" + BankMobile);
        LogUtil.d("BankCardNo:" + BankCardNo);
        LogUtil.d("BankId:" + BankId);
        LogUtil.d("IdCardImgUrl:" + IdCardImgUrl);
        LogUtil.d("BankCardImgUrl:" + BankCardImgUrl);
        LogUtil.d("HoldIdCardImgUrl:" + HoldIdCardImgUrl);
        identifyPresenter.startIdentify(mContext, jsonFormat.identify(RealName, IdCardNo, BankMobile, BankCardNo, BankId, IdCardImgUrl, BankCardImgUrl, HoldIdCardImgUrl));
    }

    private BaseFragmentBack getFragment(int position) {
        if (fragments != null && fragments.size() > 0) {
            BaseFragmentBack baseFragment = fragments.get(position);
            return baseFragment;
        }
        return null;
    }

    public void switchFragment(Fragment fromFragment, BaseFragmentBack nextFragment) {

        if (allFragments != nextFragment) {

            allFragments = nextFragment;

            if (nextFragment != null) {
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

                //判断nextFragment是否添加
                if (!nextFragment.isAdded()) {
                    //隐藏当前Fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.add(R.id.layout_content, nextFragment).commit();
                } else {
                    //隐藏当前Fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }

    @Subscribe
    public void onEvent(MessageBean bean) {
        switch (bean.getType()) {
            case 1:
                LogUtil.d("收到成功消息");
                switch (STEP) {
                    case 2:
                        IdCardImgUrl = (String) bean.getData();
                        break;
                    case 4:
                        BankCardImgUrl = (String) bean.getData();
                        break;
                    case 5:
                        HoldIdCardImgUrl = (String) bean.getData();
                        LogUtil.d("HoldIdCardImgUrl:" + HoldIdCardImgUrl);
                        break;
                    case 6:
                        HoldIdCardImgUrl = (String) bean.getData();
                        LogUtil.d("HoldIdCardImgUrl:" + HoldIdCardImgUrl);
                        break;
                }
                hideLoading();
                transFragment();
                break;
            case 2:
                LogUtil.d("收到失败消息");
                hideLoading();
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        retuqstReadPermissions();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST__PERMISSIONS)
    private void retuqstReadPermissions() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (!EasyPermissions.hasPermissions(mContext, perms)) {
            EasyPermissions.requestPermissions(this, "实名认证需要保存图片和拍照的权限", REQUEST__PERMISSIONS, perms);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        STEP = 1;
        page = 0;
//        IMGSPATH = "";
        RealName = "";
        IdCardNo = "";
        BankMobile = "";
        BankCardNo = "";
        BankId = "";
        IdCardImgUrl = "";
        BankCardImgUrl = "";
        HoldIdCardImgUrl = "";
        EMAIL = "";
        ADDRESS = "";
//        EventBus.getDefault().unregister(this);
    }


    private void crossImg(String path) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    // 这里进行下载操作...获得了图片的bitmap
                    Bitmap bitmap = crossUtil.getimage(path);
                    //下载完后才，向主线程发送Message
                    Message msg = Message.obtain();
                    msg.obj = bitmap;
                    msg.what = 1;//区分哪一个线程发送的消息
                    mHadler.sendMessage(msg);
                } catch (Exception ex) {

                }
            }
        }, 1000);
    }

    private void createUploadBitmap(Bitmap bitmap) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    // 这里进行下载操作...获得了图片的bitmap
                    String savepath = crossUtil.crossFile(bitmap);
                    //下载完后才，向主线程发送Message
                    Message msg = Message.obtain();
                    msg.obj = savepath;
                    msg.what = 2;//区分哪一个线程发送的消息
                    mHadler.sendMessage(msg);
                } catch (Exception ex) {

                }
            }
        }, 1000);
    }

    Handler mHadler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bitmap crossBitmap = (Bitmap) msg.obj;
                    createUploadBitmap(crossBitmap);
                    break;
                case 2:
                    String savePath = (String) msg.obj;
                    upload = new HttpUpload(setting.getUserID(), page, savePath, SUCCESS_CODE, FAIL_CODE);
                    upload.startUpload();
                    break;
            }
        }
    };

    @Override
    public void rebackUploadStatus() {
        startIdentify();
    }

}
